package com.thanhnx.tlg1;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;

import model.OnBottomHit;
import net.bgreco.DirectoryPicker;
import Util.Util;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class DEP extends Activity implements OnClickListener {
	private Callback listener = new Callback();
	private MyApp myApp;

	private ProgressBar loading_bar;
	private LinearLayout layout;
	private RelativeLayout rl_root;
	private LinkScrollView colA;
	private TableLayout tableColA;
	HorizontalScrollView hsvMainContent;
	private TableLayout row1;
	private LinkScrollView dataView;
	private TableLayout tableMain;
	final int ROW_HEIGHT = 40;
	final int COL_WIDTH = 80;
	final int NUM_COLS = 36;
	final int NUM_ROWS = 40;
	String[] cols = new String[NUM_COLS];
	String[] rows = new String[NUM_ROWS];
	String[][] data = new String[NUM_ROWS][NUM_COLS];
	private LinkedList<String> fileList = new LinkedList<String>();

	private long startTime = 0;
	private LoadingAsyncTask loading;

	private void getTimeConsumed(String tag) {
		Log.e(tag, System.currentTimeMillis() - startTime + "");
		startTime = System.currentTimeMillis();
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dep);
		myApp = (MyApp) this.getApplicationContext();
		startTime = System.currentTimeMillis();
		// showListOfFile();

		getTimeConsumed("Start");
		// Set up data[][] and rows[], cols[]
		DecimalFormat twoPlaces = new DecimalFormat("0.00");
		for (int i = 0; i < NUM_ROWS; i++) {
			rows[i] = "" + i;
		}
		for (int i = 0; i < NUM_COLS; i++) {
			cols[i] = numToColumn(i);
		}
		for (int i = 0; i < NUM_ROWS; i++) {
			for (int j = 0; j < NUM_COLS; j++) {
				data[i][j] = "";// twoPlaces.format(Math.random() * 1000);
			}
		}
		getTimeConsumed("Set up data[][] and rows[], cols[]");
		// Set up view
		layout = (LinearLayout) findViewById(R.id.spreadsheet);
		rl_root = (RelativeLayout) findViewById(R.id.rl_root);
		loading_bar = (ProgressBar) findViewById(R.id.loading);
		colA = (LinkScrollView) findViewById(R.id.colA);
		tableColA = (TableLayout) findViewById(R.id.tableColA);
		hsvMainContent = (HorizontalScrollView) findViewById(R.id.hsvMainContent);
		row1 = (TableLayout) findViewById(R.id.row1);
		dataView = (LinkScrollView) findViewById(R.id.data);
		tableMain = (TableLayout) findViewById(R.id.tableMain);

		loading = new LoadingAsyncTask();
		loading.execute();

		getTimeConsumed("Set up View by Id");
		// Setup ColA
		colA.setVerticalScrollBarEnabled(false);
		int size = rows.length;
		for (int i = -1; i < size; i++) {
			TableRow tr = new TableRow(this);
			tr.setMinimumHeight(Util.dipToPixel(getApplicationContext(),
					ROW_HEIGHT));
			tr.setGravity(Gravity.CENTER);
			if (i % 2 == 0) {
				tr.setBackgroundResource(R.color.header_bg);
			}
			EditText tv = new EditText(this);
			if (i >= 0) // -1 is the blank top left cell - this should really be
						// outside the scroll to look right
			{
				// tv.setText(rows[i]);
				tv.setOnFocusChangeListener(onFocusChange);
				tv.setImeActionLabel("NEXT", EditorInfo.IME_ACTION_NEXT);
				tv.setInputType(InputType.TYPE_CLASS_PHONE);
				myApp.etViews[i] = tv;
			} else {
				tv.setClickable(false);
				tv.setFocusable(false);
			}
			tr.addView(
					tv,
					new TableRow.LayoutParams(
							TableRow.LayoutParams.WRAP_CONTENT, Util
									.dipToPixel(getApplicationContext(),
											ROW_HEIGHT), 1.0f));
			tableColA.addView(tr);

		}
		getTimeConsumed("Set up ColA");
		// Setup hsvMainContent
		hsvMainContent.setVerticalScrollBarEnabled(false);
		// Setup cols heading
		TableRow trHeading = new TableRow(this);
		trHeading.setBackgroundResource(R.color.header_bg);
		trHeading.setMinimumHeight(Util.dipToPixel(getApplicationContext(),
				ROW_HEIGHT));
		for (int i = 0; i < cols.length; i++) {
			TextView tv = new TextView(this);
			tv.setGravity(Gravity.CENTER);
			tv.setText(cols[i]);// numToColumn(i));
			tv.setMinWidth(COL_WIDTH);
			trHeading.addView(tv);
		}
		row1.addView(trHeading);
		getTimeConsumed("Set up Col heading");

		// Setup main data
		dataView.setVerticalScrollBarEnabled(false);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == DirectoryPicker.PICK_DIRECTORY
				&& resultCode == RESULT_OK) {
			Bundle extras = data.getExtras();
			String path = (String) extras.get(DirectoryPicker.CHOSEN_DIRECTORY);
			if (TextUtils.isEmpty(path)) {
				return;
			}
			// do stuff with path
			Util.insertLastPath(getApplicationContext(), path);
			Toast.makeText(getApplicationContext(), path, Toast.LENGTH_SHORT)
					.show();
			Calendar c = Calendar.getInstance();
			SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
			String formattedDate = df.format(c.getTime());
//			myApp.saveData();
//			if (Util.writeToFile(getApplicationContext(), formattedDate, path,
//					myApp.datas, myApp.size)) {
//				finish();
//			}

		}
	}

	private void showListOfFile() {
		File file = Environment.getExternalStorageDirectory();
		fileList = Util.visitAllFiles(file);
		String al[] = new String[fileList.size()];
		for (int i = 0; fileList.size() > 0; i++) {
			al[i] = (String) fileList.remove();
			Log.d("file", "" + al[i]);
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(DEP.this,
				android.R.layout.simple_list_item_1, al);

		ListView lv = new ListView(DEP.this);

		lv.setBackgroundColor(0xffcccccc); // light gray
		lv.setAdapter(adapter);
		// rl_root.addView(lv);

	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.btn_save:
			intent = new Intent(getApplicationContext(), DirectoryPicker.class);
			if (!TextUtils.isEmpty(Util.GetLastPath(getApplicationContext()))) {
				// intent.putExtra(DirectoryPicker.START_DIR,
				// Util.GetLastPath(getApplicationContext()));
				// intent.putExtra(DirectoryPicker.SHOW_HIDDEN, false);
				// intent.putExtra(DirectoryPicker.ONLY_DIRS, true);
			}
			startActivityForResult(intent, DirectoryPicker.PICK_DIRECTORY);
			break;
		case R.id.btn_1:
			intent = new Intent(getApplicationContext(), Graph.class);
			startActivity(intent);
			break;
		case R.id.btn_2:
			intent = new Intent(getApplicationContext(), MainActivity.class);
			startActivity(intent);
			break;
		case R.id.btn_3:
			intent = new Intent(getApplicationContext(), ListViewActivity.class);
			startActivity(intent);
			break;

		default:
			break;
		}

	}

	private void showOptionDialog() {
		final Dialog dialog = new Dialog(this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_option);
		dialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				finish();
			}
		});
		Button btn_recent = (Button) dialog.findViewById(R.id.btn_1);
		Button btn_new = (Button) dialog.findViewById(R.id.btn_2);
		btn_recent.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
//				String[][] datas = Util.readFromFile(getApplicationContext(),
//						myApp.datas, myApp.size);
//				Log.e("got", myApp.size.row + " " + myApp.size.col);
//				for (int i = 0; i < myApp.size.row; i++) {
//					String out = "";
//					for (int j = 0; j < myApp.size.col; j++) {
//						out = out + datas[i][j] + " ";
//					}
//					Log.e("got", out);
//				}
//				myApp.bindDataToView();
				dialog.dismiss();
			}
		});
		btn_new.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
//				myApp.createBlankData();
				dialog.dismiss();
			}
		});
		dialog.show();

	}

	private class LoadingAsyncTask extends AsyncTask<Void, Void, Void> {
		private ProgressDialog dialog;
		private ArrayList<TableRow> dataviews = new ArrayList<TableRow>();

		// private EditText[][] etViews = new EditText[NUM_ROWS][NUM_COLS];

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(DEP.this);
			dialog.setCancelable(true);
			dialog.setMessage("Loading data...");
			dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			dialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			final Context context = getApplicationContext();
			// Setup main data
			final int rowSize = rows.length;
			final int colSize = cols.length;
			// runOnUiThread(new Runnable() {
			// @Override
			// public void run() {
			for (int i = 0; i < rowSize; i++) {
				final TableRow tr = new TableRow(context);
				if (i % 2 == 0) {
					tr.setBackgroundResource(R.color.cell_dark_bg);
				}
				tr.setMinimumHeight(ROW_HEIGHT);
				for (int j = 0; j < colSize; j++) {
					TextView et = new TextView(DEP.this);
					et.setMinWidth(COL_WIDTH);
					et.setText(data[i][j]);
					et.setGravity(Gravity.CENTER);
					tr.addView(et);
					myApp.tvViews[i][j] = et;
				}
				dataviews.add(tr);
			}
			// }
			// });
			getTimeConsumed("Set up Main data");
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			int size = dataviews.size();
			getTimeConsumed("Post Execute");
			for (int i = 0; i < size; i++) {
				tableMain.addView(dataviews.get(i));
			}
			colA.setListener(listener);
			dataView.setListener(listener);
			getTimeConsumed("Post Execute");
			colA.others.add(dataView);
			dataView.others.add(colA);
			dialog.dismiss();
			if (!TextUtils.isEmpty(Util.GetLastPath(getApplicationContext()))) {
				showOptionDialog();
			}
		}
	}

	private OnFocusChangeListener onFocusChange = new OnFocusChangeListener() {
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			if (!hasFocus) {
				Log.e("focus change", "update");
//				myApp.update();
			}
		}
	};

	String numToColumn(int i) {
		boolean go = true;
		String t = "";
		while (go) {
			int x = i % 26;
			String s = "";
			switch (x) {
			case 0:
				s = "Rd";
				break;
			case 1:
				s = "Blk";
				break;
			case 2:
				s = "1xS";
				break;
			case 3:
				s = "2xS";
				break;
			case 4:
				s = "3xS";
				break;
			case 5:
				s = "BBL";
				break;
			case 6:
				s = "TFL";
				break;
			case 7:
				s = "Ard";
				break;
			case 8:
				s = "Abk";
				break;

			case 9:
				s = "Evn";
				break;
			case 10:
				s = "Odd";
				break;
			case 11:
				s = "1xS";
				break;
			case 12:
				s = "2xS";
				break;
			case 13:
				s = "3xS";
				break;
			case 14:
				s = "BBL";
				break;
			case 15:
				s = "FTL";
				break;
			case 16:
				s = "Aev";
				break;
			case 17:
				s = "Aod";
				break;

			case 18:
				s = "Big";
				break;
			case 19:
				s = "Sml";
				break;
			case 20:
				s = "1xS";
				break;
			case 21:
				s = "2xS";
				break;
			case 22:
				s = "3xS";
				break;
			case 23:
				s = "BBL";
				break;
			case 24:
				s = "TFL";
				break;
			case 25:
				s = "Abg";
				break;
			case 26:
				s = "Asl";
				break;
			}

			t = s + t;
			if (i < 26)
				go = false;
			i = i / 26;
			i--;
		}
		return t;
	}

	private class Callback implements OnBottomHit {
		// addRows(5);
		@Override
		public void bottomHit() {
		}
	}

	private void addRows(int r) {
		Context context = getApplicationContext();
		Toast.makeText(context, "add rows", Toast.LENGTH_SHORT).show();
		// Set up colA
		for (int i = 0; i < r; i++) {
			TableRow tr = new TableRow(context);
			tr.setMinimumHeight(Util.dipToPixel(getApplicationContext(),
					ROW_HEIGHT));
			tr.setGravity(Gravity.CENTER);
			tr.setBackgroundResource(R.color.header_bg);
			TextView tv = new TextView(context);
			tv.setText(rows.length + i + "");
			tr.addView(tv);
			tableColA.addView(tr);
		}
		// Set up data main view
		final int colSize = cols.length;
		for (int i = 0; i < r; i++) {
			final TableRow tr = new TableRow(context);
			if (i % 2 == 0) {
				tr.setBackgroundResource(R.color.cell_dark_bg);
			}
			tr.setMinimumHeight(ROW_HEIGHT);
			for (int j = 0; j < colSize; j++) {
				EditText et = new EditText(DEP.this);
				et.setMinWidth(COL_WIDTH);
				et.setImeActionLabel("NEXT", EditorInfo.IME_ACTION_NEXT);
				et.setInputType(InputType.TYPE_CLASS_NUMBER);
				tr.addView(
						et,
						new TableRow.LayoutParams(
								TableRow.LayoutParams.WRAP_CONTENT, Util
										.dipToPixel(getApplicationContext(),
												ROW_HEIGHT), 1.0f));
			}
			tableMain.addView(tr);
		}

	}

}
